package cn.tedu.csmall.product.filter;

import cn.tedu.csmall.product.security.LoginPrincipal;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * JWT过滤器
 * @author 何惠民
 * @version 0.0.1
 */
//@Component组件 交给spring管理
@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    @Value("${csmall.jwt.secret-key}")
    String secretKey;

    public static final int JWT_MIN_LENGTH = 113;

    public JwtAuthorizationFilter() {
        log.info("创建过滤器对象JwtAuthorizationFilter");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.debug("JwtAuthorizationFilter开始执行过滤");

        //Security清空上下文
        //认证信息也会被清除
        //避免携带一次jwt后续不用携带jwt也能访问
        SecurityContextHolder.clearContext();

        //获取客户端的jwt
        String  jwt = request.getHeader("Authorization");
        log.debug("获取客户端携带的jwt:{}",jwt);

        //检查是否获取到了基本有效的jwt
        if (!StringUtils.hasText(jwt) || jwt.length() < JWT_MIN_LENGTH){
            //对于无效的JWT,直接放行,交于后续的组件进行处理
            log.debug("获取到的JWT被视为无效,当前过滤器将放行...");
            filterChain.doFilter(request,response);
            return;
        }

        //尝试解析JWT
        log.debug("获取到的JWT被视为有效,尝试解析JWT...");
        Claims claims = null;
        response.setContentType("application/json; charset=utf-8");
        try{
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        }catch (SignatureException e){
            log.debug("解析JWT时出现SignatureException异常");
            String message = "非法访问!!!";
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE,message);
            //java对象转JSON数据  使用的阿里云的fastjson
            String jsonResultString = JSON.toJSONString(jsonResult);
            //设置响应格式
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            return;
        }catch (MalformedJwtException e){
            log.debug("解析JWT时出现MalformedJwtException异常");
            String message = "非法访问!!!";
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_MALFORMED,message);
            //java对象转JSON数据  使用的阿里云的fastjson
            String jsonResultString = JSON.toJSONString(jsonResult);
            //设置响应格式
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            return;
        }catch (ExpiredJwtException e){
            log.debug("解析JWT时出现ExpiredJwtException异常");
            String message = "登录信息以过期,请重新登录!!!";
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_EXPIRED,message);
            //java对象转JSON数据  使用的阿里云的fastjson
            String jsonResultString = JSON.toJSONString(jsonResult);
            //设置响应格式
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            return;
        }catch (Throwable e){
            log.debug("解析JWT时出现Throwable，需要开发人员在JWT过滤器补充对异常的处理");
            e.printStackTrace();
            String message = "你有异常没有处理，请根据服务器端控制台的信息，补充对此类异常的处理！！！";
            PrintWriter writer = response.getWriter();
            writer.println(message);
            return;
        }

        //获取jwt中的管理员信息
        String  username = claims.get("username", String.class);
        Long id = claims.get("id",Long.class);
        String authoritiesJsonString = claims.get("authoritiesJSONString",String.class);
        log.debug("从JWT中获取id：{}", id);
        log.debug("从JWT中获取username：{}", username);
        log.debug("从JWT中获取authoritiesJsonString：{}", authoritiesJsonString);

        //处理权限信息
        List<SimpleGrantedAuthority> authorities = JSON.parseArray(authoritiesJsonString,SimpleGrantedAuthority.class);

        //创建Authentication对象
        LoginPrincipal loginPrincipal = new LoginPrincipal(id,username);
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                loginPrincipal,null,authorities);
        //将Authentication对象放入SecurityContext
        log.debug("先SecurityContext中存入认证信息{}",authentication);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        log.debug("JWT过滤器解析完毕");
        //过滤链向后传递  放行
        filterChain.doFilter(request,response);
    }
}
